<template>
  <!-- 上传 -->
  <div class="qrcode-container">
    <div class="backbar fix-bar">
      <div class="back flex-center" v-hammer:tap="(ev) => $router.push({name: 'My'})">
        <i class="fa fa-angle-left fa-lgl"></i>
        <span>返回</span>
      </div>
    </div>

    <div class="image-list-wrapper">
      <ul class="image-list" :style="{height: listHeight}">
        <li
          draggable
          @dragstart="onDragstart(item)"
          class="list-item"
          v-for="(item, i) of imageList"
          :key="i"
          v-hammer:tap="(ev) => onImageClicked(ev, item)"
          v-hammer:press="(ev) => onImagePressed(ev, item)"
        >
          <img :src="item.imageUrl" alt />
        </li>

        <li class="delete-member" v-if="imageList.length < 9">
          <div class="image-wrapper flex-center">
            <img src="@/assets/icons/plus_add.svg" alt />
          </div>
          <input type="file" accept="image/*" class="file-input" @change="onImageChange" />
        </li>
      </ul>
    </div>

    <!-- <div class="action-bar elevation-1 flexbox justify-end" @drop="onDrop">
      <div class="item">
        <span>删除</span>
      </div>
    </div>-->

    <!-- 发送图片之前的预览 -->
    <send-image-preview
      v-if="showImagePreview"
      :image="imageBase64"
      :sendText="sendText"
      :bgColor="bgColor"
      @cancel="onCancelImage"
      @send="onSendImage"
    />
  </div>
</template>

<script lang="ts">
import { Component, Vue } from "vue-property-decorator";
import { Action, Mutation, Getter, namespace } from 'vuex-class';
import { RawLocation } from "vue-router";
import { MsgTypeKV } from '@/api/socket/imClient';
import MessageMixin from '@/mixins';
import { Webim } from '@/utils/types';
import { Api } from '@/api/http';
declare const $Vue: Vue;
declare const webim: Webim;
const chatModule = namespace('chatModule');
const userModule = namespace('userModule');

@Component<Album>({
  mixins: [MessageMixin],
})
export default class Album extends Vue {
  @chatModule.State("groupSetting") groupSetting: any;
  @userModule.State("loginInfo") loginInfo: any;

  private sendText: string = '上传';
  private bgColor: any = '';

  private eventList: Array<string> = [
    "$getGroupQrcode",
    "$getImageList",
    "$deleteQrcodeImage",
  ];

  private imageList: Array<any> = [];

  // 0為發送  1 為預覽 可刪除
  private previewType: number = 0;

  private listHeight: string = '400px';

  // 预览
  private showImagePreview: boolean = false;
  private imageFile: any = null;
  private imageBase64: string = '';
  private info: any = {};
  private selectedImage: any = {};

  // 能否进行编辑
  private allowEdit: boolean = false;
  private allowSend: boolean = true;

  /**
   * 生命周期函数
   */
  protected mounted() {
    this.initEvents(this.eventList);
    this.sendMessage(MsgTypeKV.getImageList, {
      userId: localStorage.getItem('userId')
    });

    this.listHeight = window.innerWidth + 'px'
  }

  /*
   * 选取图片用于发送
   */
  private onImageChange(ev: any) {
    let file = ev.target.files[0];
    this.handleImageFile(file);
    this.imageFile = file;
    this.showImagePreview = true;
    this.previewType = 0;
    this.bgColor = '#57bd6d';
    this.sendText = '上传';
  }

  private handleImageFile(file: File) {
    const reader = new FileReader();
    // 使用base64上传
    reader.onload = (ev: any) => {
      this.imageBase64 = ev.target.result;
    };
    reader.readAsDataURL(file);
  }

  /**
   * 发送图片
   */
  private onSendImage() {
    if (this.allowSend) {
      if (this.previewType === 0) {

        if (this.isSupportFileApi()) {
          if (this.imageFile.size > 1024000) {
            this.compress(this.imageFile, (dataUrl) => {
              if (dataUrl === null) {
                this.uploadMyQrcode(this.imageFile);
              } else {
                let file = this.stringToFile(dataUrl, this.imageFile.name);
                this.uploadMyQrcode(file);
              }
            });
          } else {
            this.uploadMyQrcode(this.imageFile);
          }

        } else {
          this.$createToast({
            txt: '不支持图片压缩算法, 将上传原图',
            type: "warn",
            time: 3000
          }).show();
          this.uploadMyQrcode(this.imageFile);
        }
      } else {
        this.onDeleteImage();
      }
    }
  }

  private isSupportFileApi() {
    if (File && FileList && FileReader && Blob && FormData) {
      return true;
    }
    return false;
  }

  private stringToFile(dataUrl: string, fileName: string): File {
    let arr = dataUrl.split(',');
    let mime: any = arr[0] || [];
    mime = mime.match(/:(.*?);/)[1];
    let bstr = atob(arr[1]);
    let n = bstr.length;
    let u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    // let blob: any = new Blob([u8arr], {type: mime});
    // blob.lastModifiedDate = new Date();
    // blob.name = fileName;
    let blob = new File([u8arr], fileName, { type: mime });
    return blob;
  }

  private onCancelImage() {
    this.allowSend = true;
    this.showImagePreview = false;
    this.sendText = '上传';
    this.imageFile = null;
  }

  private onImageClicked(ev, item) {
    this.imageBase64 = item.imageUrl;
    this.selectedImage = item;
    this.showImagePreview = true;
    this.previewType = 1;
    this.bgColor = '#f44336';
    this.sendText = '删除';
  }

  /**
   * 拖拽到
   */
  private onDrop(ev: any) {
    ev.preventDefault();
    console.warn(ev);


  }

  private onDragOver(ev: DragEvent) {
    ev.preventDefault();
    return false;
  }

  /**
   * 长按事件
   */
  private onImagePressed(item) {
    console.error('onImagePressed', item);
  }

  /**
   * 长按事件
   */
  private onDragstart(item) {
    console.error('onDragstart', item);

  }

  private compress(fileObj, cb) {
    let reader = new FileReader()
    reader.readAsDataURL(fileObj)
    reader.onload = function (e: any) {
      let image = new Image();     //新建一个img标签（不嵌入DOM节点，仅做canvas操作)
      image.src = e.target.result    //让该标签加载base64格式的原图
      image.onload = function () {    //图片加载完毕后再通过canvas压缩图片，否则图片还没加载完就压缩，结果图片是全黑的
        if (image.width > 1000) {
          let canvas: any = document.createElement('canvas'), //创建一个canvas元素
            context = canvas.getContext('2d'),    //context相当于画笔，里面有各种可以进行绘图的API
            imageWidth = image.width / 2,    //压缩后图片的宽度，这里设置为缩小一半
            imageHeight = image.height / 2,    //压缩后图片的高度，这里设置为缩小一半
            data = ''    //存储压缩后的图片
          canvas.width = imageWidth    //设置绘图的宽度
          canvas.height = imageHeight    //设置绘图的高度

          //使用drawImage重新设置img标签中的图片大小，实现压缩。drawImage方法的参数可以自行查阅W3C
          context.drawImage(image, 0, 0, imageWidth, imageHeight)
          //使用toDataURL将canvas上的图片转换为base64格式
          data = canvas.toDataURL('image/jpeg');
          if (cb) {
            cb(data);
          }
        } else {
          if (cb) {
            cb(null);
          }
        }
        //将压缩后的图片显示到页面上的img标签
      }
    }
  }
  /**
     * 删除二维码
     */
  private onDeleteImage() {
    this.$createDialog({
      type: 'confirm',
      icon: 'cubeic-alert',
      title: '确认删除该图片吗?',
      confirmBtn: {
        text: '确定',
        active: true,
        disabled: false,
        href: 'javascript:;'
      },
      cancelBtn: {
        text: '取消',
        active: false,
        disabled: false,
        href: 'javascript:;'
      },
      onConfirm: () => {
        this.sendMessage(MsgTypeKV.deleteQrcodeImage, {
          galId: this.selectedImage.galId,
        });
        // this.allowSend = true;
        // this.sendText = '上传';
      },
      onCancel: () => {
        // this.sendText = '上传';
        // this.allowSend = true;

        // this.amount = '0';
        // this.number = '1';
      }
    }).show();
  }

  /**
   * 获取到用户qrcode
   */
  private $getImageList(data: any) {
    if (data.result === 0) {
      this.imageList = data.imageList;
    } else {
      this.imageList = []
    }
  }


  /**
   * 删除用户qrcode
   */
  private $deleteQrcodeImage(data: any) {
    if (data.result === 0) {
      // this.imageList = data.imageList;
      this.sendMessage(MsgTypeKV.getImageList);
      this.showImagePreview = false;

    }
  }

  /**
   * 上传二维码
   */
  private async uploadMyQrcode(file: File) {
    let token: any = sessionStorage.getItem("token");
    let form: FormData = new FormData();
    form.append('file', file);
    const params = {
      token,
      form,
    };
    this.allowSend = false;
    this.sendText = '上传中';
    const { data } = await Api.uploadMyQrcode.r(params);
    console.warn('uploadMyQrcode', data);
    this.imageFile = null;
    this.showImagePreview = false;
    if (data.result === 0) {
      this.$createToast({
        txt: '上传成功',
        type: "correct",
        time: 3000
      }).show();
      this.sendText = '上传';
      this.allowSend = true;
      this.sendMessage(MsgTypeKV.getImageList);
    } else {
      this.sendText = '上传';
      this.allowSend = true;
      this.$createToast({
        txt: data.message,
        type: "warn",
        time: 3000
      }).show();

    }
  }

  /**
   * 获取群已有的
   */
  private $getGroupQrcode(data: any) {
    if (data.result === 0) {
      // this.qrUrl = data.qrUrl;
    } else {
      this.$createToast({
        txt: data.message,
        type: "warn",
        time: 3000
      }).show();
    }
  }
}
</script>

<style lang="stylus" scoped>
.qrcode-container
  background #f1f1f1
  width 100% 
  height 100% 
.image-list-wrapper
  display flex 
  justify-content center
  .image-list
    display flex
    justify-content flex-start
    align-items flex-start
    flex-wrap wrap
    padding 8px 
    align-content flex-start
    box-sizing border-box
    width 100% 
    li
      margin-top 3%
      margin-left 1.5%
      margin-right 1.5%
      border-radius 2px
      width 30%
      height 30%
      img
        width 90%
        height 90%
        border-radius 4px
      .username 
        font-size 12px
        color #898989
        margin-top 2px

.delete-member
  position relative
  .image-wrapper
    border-radius 4px
    border 1.5px solid #e2e2e2
    height 90%
    img
      width 40%!important

.action-bar
  position fixed 
  width 100% 
  height 56px 
  bottom 0
  left 0
  background #f44336 
  color white
</style>

